﻿using System;
using System.Web.UI.WebControls;
using MyLib.Data;

namespace MyLib.Web.Pages {
	/// <summary>
	/// 
	/// </summary>
	public class ConfigPage : MyPage {
		/// <summary>
		/// 
		/// </summary>
		private const int DefaultApplicationId = 1;

		/// <summary>
		/// 
		/// </summary>
		protected int ApplicationId {
			get {
				var obj = ViewState["ApplicationId"];
				if (obj == null) {
					return DefaultApplicationId;
				} else {
					return (int)obj;
				}
			}
			set {
				ViewState["ApplicationId"] = value;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			Title = Properties.Main.TitleConfig;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="source"></param>
		/// <param name="args"></param>
		/// <returns></returns>
		protected override bool OnBubbleEvent(object source, EventArgs args) {
			bool causesValidation = false;
			string validationGroup = string.Empty;

			if (args is CommandEventArgs) {
				IButtonControl commandSource = source as IButtonControl;
				if (commandSource != null) {
					causesValidation = commandSource.CausesValidation;
					validationGroup = commandSource.ValidationGroup;
				}

				var cargs = (CommandEventArgs)args;

				if (string.Equals(cargs.CommandName, "ResetAdminUser", StringComparison.OrdinalIgnoreCase)) {
					HandleResetAdminUser(causesValidation, validationGroup);
					return true;
				} else if (string.Equals(cargs.CommandName, "ExportCodes", StringComparison.OrdinalIgnoreCase)) {
					HandleExportCodes(causesValidation, validationGroup);
					return true;
				} else if (string.Equals(cargs.CommandName, "ClearCodes", StringComparison.OrdinalIgnoreCase)) {
					HandleClearCodes(causesValidation, validationGroup);
					return true;
				} else if (string.Equals(cargs.CommandName, "ImportCodes", StringComparison.OrdinalIgnoreCase)) {
					HandleImportCodes(causesValidation, validationGroup);
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="causesValidation"></param>
		/// <param name="validationGroup"></param>
		private void HandleExportCodes(bool causesValidation, string validationGroup) {
			var cfp = new CodeFileProvider(MapPath("~/SysCode.xml"));
			var cp = GetDbProvider<CodeProvider>();

			var table = cp.FindCodes();
			cfp.SaveDataTable(table);

			Context.AddInformation("All codes has been exported.");
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="causesValidation"></param>
		/// <param name="validationGroup"></param>
		private void HandleClearCodes(bool causesValidation, string validationGroup) {
			var cp = GetDbProvider<CodeProvider>();

			cp.DeleteCode();

			Context.AddInformation("All codes has been clear.");
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="causesValidation"></param>
		/// <param name="validationGroup"></param>
		private void HandleImportCodes(bool causesValidation, string validationGroup) {
			var cfp = new CodeFileProvider(MapPath("~/SysCode.xml"));
			var cp = GetDbProvider<CodeProvider>();

			var table = cfp.LoadDataTable();
			foreach (var row in table) {
				cp.SaveCode(row.CategoryId, row.Value,
					row.IsTextNull ? string.Empty : row.Text,
					row.IsParentNull ? null : row.Parent);
			}

			Context.AddInformation("All codes has been imported.");
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="causesValidation"></param>
		/// <param name="validationGroup"></param>
		private void HandleResetAdminUser(bool causesValidation, string validationGroup) {
			var acp = GetDbProvider<MyLib.Data.AuthorityProvider>();

			var rdt = acp.FindRoleByName(ApplicationId, "administrators");
			string roleId = "";
			if (rdt.Count != 0) {
				roleId = rdt[0].RoleId;
			}

			acp.SaveRole(ApplicationId, ref roleId, "administrators", "administrators", "101,102,103,104,105,106,107,108,109,110,201,202,203,204,205,206,207,208,209,210");

			var dt = acp.FindUserByName("admin");
			string userId = "";
			if (dt.Count != 0) {
				userId = dt[0].UserId;
				acp.ResetPassword(userId);
				acp.DeleteUserExt(userId);
			}

			var c = acp.SaveUser(ApplicationId, ref userId, "admin", "administrator", null, 1, roleId);

			if (c == 1) {
				Context.AddInformation("Admin user has been reset.");
			}
		}
	} // end of ConfigPage.
}
